const express = require('express')
const dayjs = require('dayjs')
const router = express.Router()
const Shop = require('../db/model/shopModel')
const { formatDateTime } = require('../utils/time');

/**
 * @api {post} /shop/add 商品添加
 * @apiName 商品添加
 * @apiGroup Shop
 *
 * @apiParam {String} status 购买等级 1 2 3 紧急、次要、未来
 * @apiParam {String} shopname 商品名
 * @apiParam {String} mark 备注
 * @apiParam {Number} time 购买时间
 * @apiParam {String} createtime 创建时间
 * @apiParam {String} username 用户
 */
router.post('/add', (req, res) => {

  const { status, shopname, mark, time } = req.body
  const { username: originUsername } = req.headers
  const username = decodeURIComponent(originUsername)

  if(!username){
    res.send({ code: 500, msg: '未登录' })
    return
  }

  if(!shopname){
    res.send({ code: 500, msg: '商品必填' })
    return
  }

  Shop.find({ shopname, username })
    .then((data) => {
      if (data.length === 0) {
        return Shop.insertMany({ status, shopname, mark, time, username, createtime:  dayjs().format('YYYY-MM-DD')})
      } else {
        // 商品已存在
        return -1
      }
    })
    .then((e) => {
      if(e===-1){
        res.send({ code: 500, msg: '商品已存在' })
        return
      }
      res.send({ code: 200, msg: '添加成功' })
    })
    .catch((e) => {
      console.log(e)
      res.send({ code: 500, msg: '添加失败' })
    })
})

/**
 * @api {post} /shop/del 删除
 * @apiName 删除
 * @apiGroup Shop
 *
 * @apiParam {Number} shopname 商品名
 */
router.post('/del', (req, res) => {
  const { shopname } = req.body

  const { username: originUsername } = req.headers
  const username = decodeURIComponent(originUsername)

  if(!username){
    res.send({ code: 500, msg: '未登录' })
    return
  }

  Shop.remove({ shopname, username })
    .then(() => {
      res.send({ code: 200, msg: '删除成功' })
    })
    .catch(() => {
      res.send({ code: 500, msg: '删除失败' })
    })
})

/**
 * @api {post} /shop/update 商品修改
 * @apiName 商品修改
 * @apiGroup Shop
 *
 * @apiParam {String} status 购买等级 1 2 3 紧急、次要、未来
 * @apiParam {String} shopname 原商品名
 * @apiParam {String} newshopname 新商品名
 * @apiParam {String} mark 备注
 * @apiParam {Number} time 购买时间
 * @apiParam {String} createtime 创建时间
 * @apiParam {String} updatetime 更新时间
 * @apiParam {String} username 用户
 */
router.post('/update', (req, res) => {
  const { status, shopname, newshopname, mark, time } = req.body

  const { username: originUsername } = req.headers
  const username = decodeURIComponent(originUsername)

  
  if(!username){
    res.send({ code: 500, msg: '未登录' })
    return
  }
  Shop.updateOne({ shopname, username }, { status, shopname: newshopname, mark, time, username, updatetime:  dayjs().format('YYYY-MM-DD') })
    .then((e) => {
      if(e.nModified === 1){
        res.send({ code: 200, msg: '修改成功' })
        return
      }
      res.send({ code: 500, msg: '修改失败' })
     
    })
    .catch(() => {
      res.send({ code: 500, msg: '修改失败' })
    })
})

/**
 * @api {post} /shop/page 商品列表
 * @apiName 商品列表
 * @apiGroup Shop
 *
 * @apiParam {Number} pageNo 页数
 * @apiParam {Number} pageSize 条数
 * @apiParam {Number} key 关键字查询
 */
router.post('/list', (req, res) => {
  const pageNo = Number(req.body.pageNo) || 1
  const pageSize = Number(req.body.pageSize) || 10
  const shopname = req.body.shopname
  const status = req.body.status

  const { username: originUsername } = req.headers
  const username = decodeURIComponent(originUsername)

  if(!username){
    res.send({ code: 500, msg: '未登录' })
    return
  }

  const reg = new RegExp(username)
  let query = { $or: [{ username:  {$regex: reg}}] }
  if(shopname){
    query['$or'][0].shopname = {$regex: new RegExp(shopname)}
  }
  if(status){
    query['$or'][0].status = Number(status)
  }
  Shop.countDocuments(query, (err, count) => {
    if (err) {
      res.send({ code: 500, msg: '商品列表获取失败' })
      return
    }
    Shop.aggregate([
        {
            $match: query
        },
        {
            $skip: pageSize * (pageNo - 1)
        },
        {
            $limit: pageSize
        },
        {
          // $project中的字段值 为1表示筛选该字段，为0表示过滤该字段
          $project: { foodtypes: { _id: 0 } }
        }
    ], function(err, docs) {
        if (err) {
            res.send({ code: 500, msg: '商品列表获取失败' })
            return;
        }
        res.send({
            code: 200,
            data: docs,
            total: count,
            pageNo: pageNo,
            pageSize: pageSize,
            msg: '商品列表获取成功',
        })
    })
  })
})

module.exports = router
